package cn.wolfcode.p2p.bussness.service.impl;

import cn.wolfcode.p2p.base.query.QueryObject;
import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.bussness.domain.SystemAccount;
import cn.wolfcode.p2p.bussness.domain.SystemAccountFlow;
import cn.wolfcode.p2p.bussness.mapper.SystemAccountFlowMapper;
import cn.wolfcode.p2p.bussness.service.ISystemAccountFlowService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SystemAccountFlowServiceImpl implements ISystemAccountFlowService {

    @Autowired
    private SystemAccountFlowMapper systemAccountFlowMapper;

    @Override
    public int save(SystemAccountFlow systemAccountFlow) {
        return systemAccountFlowMapper.insert(systemAccountFlow);
    }

    @Override
    public PageInfo queryPage(QueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        List<SystemAccountFlow> list = systemAccountFlowMapper.selectList(qo);
        return new PageInfo(list);
    }

    /**
     *
     * @param systemAccount 系统账户
     * @param amount   修改的金额
     * @param note      备注信息
     * @param actionType     系统账户流水类型
     */
    private void createFlow(SystemAccount systemAccount, BigDecimal amount, String note, int actionType) {
        SystemAccountFlow accountFlow = new SystemAccountFlow();
        //交易时间
        accountFlow.setActionTime(new Date());
        //交易金额
        accountFlow.setAmount(amount);
        //交易类型
        accountFlow.setActionType(actionType);
        //备注信息
        accountFlow.setNote(note);
        //交易后的可用金额
        accountFlow.setUsableAmount(systemAccount.getUsableAmount());
        //交易后的冻结金额
        accountFlow.setFreezeAmount(systemAccount.getFreezedAmount());
        //保存到数据库
        this.save(accountFlow);
    }

    @Override
    public void createGainAccountManagementChargeSuccessFlow(SystemAccount systemAccount, BigDecimal amount) {
        createFlow(systemAccount,amount,"还款体验金手续费: " + amount + "元", Constants.SYSTEM_ACCOUNT_ACTIONTYPE_EXPACCOUNT_MANAGE_CHARGE);
    }

    @Override
    public void createGainAccountManagementChargeFlow(SystemAccount systemAccount, BigDecimal amount) {
        createFlow(systemAccount,amount,"收取用户借款手续费: " + amount + "元", Constants.SYSTEM_ACCOUNT_ACTIONTYPE_MANAGE_CHARGE);
    }
}
